package com.sl.hx.shop.base;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.trello.rxlifecycle2.components.support.RxFragment;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by hwg on 2017/4/26.
 */

public abstract class BaseFragment<V , T extends BasePresenter<V>> extends RxFragment implements BaseFragmentView {

    protected Context mContext ;
    protected Activity mActivity ;
    protected T mPresenter ;

    protected Unbinder unbinder ;

    protected View mView ;

    /**
     * 创建Presenter
     * @return
     */
    protected abstract T createPresenter() ;

    /**
     * 获取fragment的布局id
     * @return
     */
    protected abstract @LayoutRes
    int getViewLayoutId() ;

    /**
     * 数据和逻辑处理
     * @param mView
     */
    protected abstract void initView(View mView) ;

    @Override
    public <T> LifecycleTransformer<T> bindToLife(FragmentEvent fragmentEvent) {
        return this.<T>bindUntilEvent(fragmentEvent);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = getContext() ;
        mActivity = getActivity() ;

        if (createPresenter() != null) {
            mPresenter = createPresenter();
            mPresenter.attachView((V) this);
        }

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        mView = inflater.inflate(getViewLayoutId() , container , false) ;

        unbinder = ButterKnife.bind(this , mView) ;

        initView(mView);

        return mView ;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();          //清除fragment的引用
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 不带参数，从Fragment跳转到指定Activity
     * @param activity
     */
    protected void toActivity(Class<?> activity){
        startActivity(new Intent(getContext(), activity));
    }

    /**
     * 带整型参数，从Fragment跳转到指定Activity
     *
     * @param activity
     * @param key
     * @param value
     */
    protected void toActivity(Class<?> activity, String key, int value){
        Intent intent = new Intent(getContext(), activity) ;
        intent.putExtra(key, value);
        startActivity(intent);
    }

}
